package middleware

import (
	"admin-server/libs"
	"admin-server/models"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 登陆权限 - 中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("Authorization")
		if token == "" {
			ctx.AbortWithStatus(401)
			return
		}
		// fmt.Println(token)
		ret := libs.CheckAccessToken(token)
		if ret == 0 {
			ctx.AbortWithStatus(401)
			return
		}
		ctx.Set("account_id", ret)
		db := libs.GetDb()
		var admin models.Admin

		err := db.Where("id=?", ret).First(&admin).Error
		if errors.Is(err, gorm.ErrRecordNotFound) {
			ctx.AbortWithStatus(401)
			return
		}
		if admin.Status == models.AdminStatusDisabled {
			ctx.AbortWithStatus(401)
			return
		}
		ctx.Set("account_info", admin)

		ctx.Next()
	}
}
